import { RequestInput, UpdateRequestInput } from "../schemas/request.schemas";
import { Request, Response } from 'express';
import requestService from '../services/request.service';
import friendService from "../services/friend.service";
import groupService from "../services/group.service";
import processMessage, { sendUserMessage, sendGroupMessage } from "../websocket/process";
import { MessageType } from "@prisma/client";

const GROUP_NEED_VALIDATION_COUNT = 20
class RequestController {
    async request(req: Request, res: Response) {
        const { userId } = req.auth;
        const { contactId, isGroup, message } = req.body as RequestInput;

        if (userId == contactId) {
            res.status(400).json({ message: 'can not request yourself' });
        }

        if (!isGroup) {
            const userFriend = await friendService.getUserFriend(contactId, userId);
            if (userFriend) {
                res.status(400).json({ message: 'he is your friend' });
                return
            }
            const request = await requestService.createFriendRequest({ senderId: userId, receiverId: contactId, message });
            sendUserMessage('request', request, contactId)
        } else {
            const groupUser = await groupService.getGroupUser(userId, contactId);
            if (groupUser) {
                res.status(400).json({ message: 'you are in this group' });
                return
            }
            //入群策略，低于20人直接进入，高20人管理员审核。另外支持邀请后直接进入。
            const memberCount = await groupService.getGroupMemberCount(contactId)
            if (memberCount < GROUP_NEED_VALIDATION_COUNT) {
                const groupMember = await groupService.createGroupMember(contactId, userId)
                const newMessage = {
                    senderId: userId,
                    groupId: contactId,
                    type: 'SYSTEM' as MessageType,
                    content: `${groupMember.user.nickname}加入群聊`
                }
                await processMessage(newMessage)
            } else {
                const request = await requestService.createGroupRequest({ senderId: userId, groupId: contactId, message });
                const groupAdmins = await groupService.getGroupAdmins(contactId);
                for (const admin of groupAdmins) {
                    sendUserMessage('request', request, admin.userId)
                }
            }
        }
        res.send({ message: 'request success' });
    }
    async process(req: Request, res: Response) {
        const { userId } = req.auth;
        const { id, status } = req.body as UpdateRequestInput;

        const request = await requestService.getRequestById(Number(id))
        if (!request || request.status !== 'PENDING') {
            res.status(400).json({ message: "request not found" })
            return
        }
        if (request.receiverId && request.receiverId !== userId) {
            res.status(400).json({ message: "not your request" })
            return
        }

        const groupUser = request.groupId ? await groupService.getGroupUser(userId, request.groupId) : null;
        if (request.groupId && groupUser?.role == 'MEMBER') {
            res.status(400).json({ message: "you are not group admin" });
            return
        }

        const requestInfo = await requestService.updateRequest(id, status);
        if (request.receiverId) {
            sendUserMessage('request', requestInfo, request.receiverId)
            if (status == 'ACCEPTED') {
                const friend1 = await friendService.createFriend(request.receiverId, request.senderId);
                const friend2 = await friendService.createFriend(request.senderId, request.receiverId)
                sendUserMessage('contact', friend1, request.senderId)
                sendUserMessage('contact', friend2, request.receiverId)
                sendUserMessage('request', requestInfo, request.senderId)

                const validateMessage = {
                    senderId: request.senderId,
                    receiverId: request.receiverId,
                    type: 'TEXT' as MessageType,
                    content: request.message
                }
                const newMessage = {
                    senderId: request.senderId,
                    receiverId: request.receiverId,
                    type: 'SYSTEM' as MessageType,
                    content: `以上是验证消息`
                }
                await processMessage(validateMessage)
                await processMessage(newMessage)
            }
        } else {
            const groupAdmins = await groupService.getGroupAdmins(requestInfo.groupId);
            for (const admin of groupAdmins) {
                sendUserMessage('request', requestInfo, admin.userId)
            }
            if (status == 'ACCEPTED') {
                groupService.createGroupMember(request.groupId, request.senderId, 'MEMBER')
                const newMessage = {
                    senderId: request.senderId,
                    groupId: request.groupId,
                    type: 'SYSTEM' as MessageType,
                    content: `${request.senderId}加入群聊`
                }
                await processMessage(newMessage)
            }
        }
        res.send({ message: 'process success', requestInfo });
    }
}

const requestController = new RequestController()
export default requestController